package org.kepler.chat.api.infra.handler;

import net.sf.json.JSONObject;
import org.bigdata.frame.exception.BizException;
import org.bigdata.frame.util.ReturnDatas;
import org.kepler.chat.api.infra.util.ErrorCode;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		// Expose ModelAndView for chosen error view.
		logger.error(ex.getMessage(), ex);
		String viewName = determineViewName(ex, request);
		if (viewName != null) {// JSP格式返回
			if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
					.getHeader("X-Requested-With")!= null && request
					.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
				// 如果不是异步请求
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			} else {// JSON格式返回
				int code = ErrorCode.SYS_ERROR.getCode();
				String msg = ErrorCode.SYS_ERROR.getMessage();
				if(ex instanceof BizException){
					code = ((BizException) ex).getErrorCode();
					msg = ((BizException) ex).getErrorMessage();
				}
				printWrite(code, msg, response);
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 将错误信息添加到response中
	 *
	 * @param msg
	 * @param response
	 * @throws IOException
	 */
	public static void printWrite(int code, String msg, HttpServletResponse response) {
		try {
			ReturnDatas returnDatas = ReturnDatas.getErrorReturnDatas();
			returnDatas.setStatusCode(""+code);
			returnDatas.setMessage(msg);

			JSONObject j = JSONObject.fromObject(returnDatas);
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			PrintWriter pw = response.getWriter();
			pw.write(j.toString());
			pw.flush();
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
